﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using ControllerExtensibility.Models;

namespace ControllerExtensibility.Controllers
{
    /*
     *  The underlying ASP.NET platform maintains a pool of .NET threads that are used to process client
    requests. This pool is called the worker thread pool, and the threads are called worker threads. When a
    request is received, a worker thread is taken from the pool and given the job of processing the request.
        When the request has been processed, the worker thread is returned to the pool, so that it is available to
    process new requests as they arrive. There are two key benefits of using thread pools for ASP.NET
    applications:
    • By reusing worker threads, you avoid the overhead of creating a new one each time
    you process a request.
    • By having a fixed number of worker threads available, you avoid the situation where
    you are processing more simultaneous requests than your server can handle.
        The worker thread pool works best when requests can be processed in a short period of time. This is
    the case for most MVC applications. However, if you have actions that depend on other servers and take a
    long time to complete, then you can reach the point where all of your worker threads are tied up waiting
    for other systems to complete their work.
     * 
     * Asynchronous controllers are useful only for actions that are I/O- or network-bound and not CPU-intensive.
     * 
     * The pool is intended to ensure that each request gets a decent slice of the server resources, but you end up with a set of worker threads that are doing nothing.
     * */
    public class RemoteDataController : AsyncController
    {
        //The problem here is that the worker thread that was handling our request was idle for two seconds—it
        //wasn’t doing anything useful, and it was not available for handling other requests while it was waiting.
        //public ActionResult Data()
        //{
        //    RemoteService service = new RemoteService();
        //    string data = service.GetRemoteData();
        //    return View((object)data);
        //}

        //async action (pag 469)
        public async Task<ActionResult> Data()
        {
            string data = await Task<string>.Factory.StartNew(() => new RemoteService().GetRemoteData());
            return View((object)data);
        }

        public async Task<ActionResult> ConsumeAsyncMethod()
        {
            string data = await new RemoteService().GetRemoteDataAsync();
            return View("Data", (object)data);
        }
    }
}
